package com.wjh.util;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @ProjectName: jk-a-parent
 * @Package: com.jiakai.utils
 * @Description:
 * @Author: HCQ
 * @CreateDate: 2018/12/14 14:59
 * @UpdateRemark:
 * @Version: 1.0
 */
public class IpUtil {
    /**
     * 获取客户端真实ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip == null) {
            ip = "";
        }

        ip = ip.replace(",", " ");
        ip = ip.trim();
        //--ip = ip.replace("127.0.0.1", "");

        String[] ips = ip.split(" ");
        if (ips.length >= 2){
            ip = ips[0];
        }

        return ip.trim();
    }
}
